package cn.lj.controller;


import cn.hutool.core.map.MapUtil;
import cn.lj.entity.User;
import cn.lj.response.Result;
import cn.lj.response.ResultCode;
import cn.lj.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.Map;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author 李津
 * @since 2021-05-19
 */
@RestController
@RequestMapping("/test")
@Api(value = "测试模块",tags = "系统测试接口")
public class TestController {
    //构造器注入
    private final UserService userService;

    private final BCryptPasswordEncoder bCryptPasswordEncoder;

    @Autowired
    public TestController(UserService userService, BCryptPasswordEncoder bCryptPasswordEncoder) {
        this.userService = userService;
        this.bCryptPasswordEncoder = bCryptPasswordEncoder;
    }

    @GetMapping("/exception")
    @ApiOperation(value = "测试异常",notes = "异常test")
    public Result testException(){
        try {
//            int i =1/0;
            List<User> users = userService.list();
            return Result.ok().data(users);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error(ResultCode.ARITHMETIC_EXCEPTION);
        }
    }

    //需要Admin角色权限：
    @PreAuthorize("hasRole('admin')")
    @GetMapping("/pass")
    @ApiOperation(value = "测试超级权限",notes = "登录test")
    public Result testLogin(){
        String password = bCryptPasswordEncoder.encode("123456");
        boolean matches = bCryptPasswordEncoder.matches("123456", password);

        System.out.println("密文：" + password);
        System.out.println("匹配结果：" + matches);

        Map<Object, Object> mp = MapUtil.builder()
                .put("password", password)
                .put("marches", matches)
                .build();
        return Result.ok().data(mp);
    }


    //需要列出用户的操作权限
    @PreAuthorize("hasAuthority('sys:user:list')")
    @GetMapping("/user")
    @ApiOperation(value = "测试列出用户的操作权限",notes = "列出用户")
    public Result findUsers(){
        List<User> users = userService.list();
        return Result.ok().data(users);
    }
}

